/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "bundle_mgr_interface.h"
#include "bundle_mgr_proxy.h"
#include "i_service.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
#include "utils_log_wrapper.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

using namespace std;
using namespace OHOS;

static void TestBundleMgr()
{
    auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    LOGE("Get samgr %{public}p", samgr.GetRefPtr());

    auto remote = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
    LOGE("Get remote %{public}p", remote.GetRefPtr());

    auto proxy = std::make_unique<AppExecFwk::BundleMgrProxy>(remote);
    LOGE("Get proxy gets %{public}d", proxy->GetUidByBundleName("test-sa", 0));
}

void OperateOnFd(int fd)
{
    const string str = "cilect write\r\n";
    lseek(fd, 0, SEEK_END);
    auto ret = write(fd, str.c_str(), str.length());
    if (ret < 0) {
        LOGI("write error %{public}d %{public}s", errno, strerror(errno));
    }
    close(fd);
}

static void TestTutorial()
{
    auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    LOGE("Get samgr %{public}p", samgr.GetRefPtr());

    auto remote = samgr->GetSystemAbility(TUTORIAL_SA_ID);
    LOGE("Get remote %{public}p", remote.GetRefPtr());

    auto proxy = iface_cast<Tutorial::IService>(remote);
    LOGE("Get proxy %{public}p", proxy.GetRefPtr());

    proxy->EchoServer("hello, world");
    proxy->DumpObj({12, 34});

    int fd = proxy->GetFd();
    OperateOnFd(fd);
}

int main(int argc, char const *argv[])
{
    TestBundleMgr();
    TestTutorial();

    return 0;
}
